<script setup>
import { ref, computed } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { interfaceListService, interfaceAddService, interfaceUpdateService, interfaceDeleteService } from '@/api/iimApi/interface.js';
import { interfaceTypeListService } from '@/api/biApi/interface_types.js';
import { ioTypeListService } from '@/api/biApi/io_types.js';
import { objectListService } from '@/api/iimApi/object.js';
import { useProjectStore } from '@/stores/projectStore';

// 获取项目存储
const projectStore = useProjectStore();

// 接口列表数据模型
const interfaces = ref([]);
const filteredInterfaces = ref([]);
const interfaceName = ref('');

// 分页条数据模型
const pageNum = ref(1); // 当前页
const total = ref(0); // 总条数
const pageSize = ref(3); // 每页条数

// 控制抽屉是否显示
const visibleDrawer = ref(false);
const isEdit = ref(false); // 控制是否为编辑状态

// 添加表单数据模型
const interfaceModel = ref({
  id: null,
  name: '',
  identifier: '',
  interfaceTypeId: '',
  objectTypeId: '',
  ioTypeId: '',
  description: '',
  rules: ''
});

// 接口类型、IO类型、所属对象数据模型
const interfaceTypes = ref([]);
const ioTypes = ref([]);
const objects = ref([]);

// 打开添加接口表单
const openAddInterface = () => {
  isEdit.value = false;
  interfaceModel.value = {
    id: null,
    name: '',
    identifier: '',
    interfaceTypeId: '',
    objectTypeId: '',
    ioTypeId: '',
    description: '',
    rules: ''
  };
  visibleDrawer.value = true;
};

// 获取接口列表数据
const interfaceList = async () => {
  let result = await interfaceListService(projectStore.selectedProject.id);

  // 渲染视图
  interfaces.value = result.data.map(item => ({
    id: item.id,
    name: item.name,
    identifier: item.identifier,
    interfaceTypeId: item.interfaceTypeId,
    objectTypeId: item.objectTypeId,
    ioTypeId: item.ioTypeId,
    description: item.description,
    rules: item.rules,
    interfaceTypeName: interfaceTypes.value.find(type => type.id === item.interfaceTypeId)?.type || '',
    objectTypeName: objects.value.find(object => object.id === item.objectTypeId)?.name || '',
    ioTypeName: ioTypes.value.find(ioType => ioType.id === item.ioTypeId)?.type || ''
  }));
  filteredInterfaces.value = interfaces.value;
  total.value = filteredInterfaces.value.length;
};

// 获取接口类型列表数据
const getInterfaceTypes = async () => {
  let result = await interfaceTypeListService();
  interfaceTypes.value = result.data;
};

// 获取IO类型列表数据
const getIoTypes = async () => {
  let result = await ioTypeListService();
  ioTypes.value = result.data;
};

// 获取所属对象列表数据
const getObjects = async () => {
  let result = await objectListService(projectStore.selectedProject.id);
  objects.value = result.data;
};

// 初始化数据
const initData = async () => {
  await getInterfaceTypes();
  await getIoTypes();
  await getObjects();
  await interfaceList();
};

// 计算当前页显示的数据
const paginatedInterfaces = computed(() => {
  const start = (pageNum.value - 1) * pageSize.value;
  const end = start + pageSize.value;
  return filteredInterfaces.value.slice(start, end);
});

// 当每页条数发生了变化，调用此函数
const onSizeChange = (size) => {
  pageSize.value = size;
  interfaceList();
};

// 当前页码发生变化，调用此函数
const onCurrentChange = (num) => {
  pageNum.value = num;
  interfaceList();
};

// 过滤接口列表
const filterInterfaces = () => {
  const query = interfaceName.value.toLowerCase();
  filteredInterfaces.value = interfaces.value.filter(interfaceItem => 
    interfaceItem.name.toLowerCase().includes(query) || 
    interfaceItem.identifier.toLowerCase().includes(query)
  );
  total.value = filteredInterfaces.value.length;
};

// 重置搜索
const resetSearch = () => {
  interfaceName.value = '';
  filterInterfaces();
};

// 添加接口
const addInterface = async () => {
  let result;
  if (isEdit.value) {
    result = await interfaceUpdateService(interfaceModel.value, projectStore.selectedProject.id);
    ElMessage.success(result.msg ? result.msg : '修改成功');
  } else {
    result = await interfaceAddService(interfaceModel.value, projectStore.selectedProject.id);
    ElMessage.success(result.msg ? result.msg : '添加成功');
  }
  visibleDrawer.value = false;
  interfaceList();
};

// 编辑接口
const editInterface = (interfaceItem) => {
  isEdit.value = true;
  interfaceModel.value = { ...interfaceItem };
  visibleDrawer.value = true;
};

// 删除接口
const deleteInterface = async (interfaceItem) => {
  try {
    await ElMessageBox.confirm(
      `此操作将永久删除接口 "${interfaceItem.name}" 及其所有关联的元素信息, 是否继续?`,
      '警告',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    );
    await interfaceDeleteService(interfaceItem.id, projectStore.selectedProject.id);
    ElMessage.success('删除成功');
    interfaceList();
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败');
    }
  }
};

// 表单校验规则
const rules = {
  name: [{ required: true, message: '请输入接口名称', trigger: 'blur' }],
  identifier: [{ required: true, message: '请输入接口标识', trigger: 'blur' }],
  description: [{ required: false, message: '请输入接口描述', trigger: 'blur' }],
  rules: [{ required: false, message: '请输入接口规则', trigger: 'blur' }]
};

// 初始化接口列表
initData();
</script>

<template>
  <el-card class="page-container">
    <template #header>
      <div class="header">
        <span>外部接口信息管理</span>
        <div class="extra">
          <el-button type="primary" @click="openAddInterface">添加接口</el-button>
        </div>
      </div>
    </template>
    <!-- 搜索表单 -->
    <el-form inline>
      <el-form-item label="接口名称或标识：">
        <el-input placeholder="请输入接口名称或标识" v-model="interfaceName"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="filterInterfaces">搜索</el-button>
        <el-button @click="resetSearch">重置</el-button>
      </el-form-item>
    </el-form>
    <!-- 接口信息列表 -->
    <el-table :data="paginatedInterfaces" style="width: 100%">
      <el-table-column prop="name" label="接口名称" width="100" show-overflow-tooltip></el-table-column>
      <el-table-column prop="identifier" label="接口标识" width="100" show-overflow-tooltip></el-table-column>
      <el-table-column prop="interfaceTypeName" label="接口类型" width="100" show-overflow-tooltip></el-table-column>
      <el-table-column prop="objectTypeName" label="所属对象" width="100" show-overflow-tooltip></el-table-column>
      <el-table-column prop="ioTypeName" label="IO类型" width="100" show-overflow-tooltip></el-table-column>
      <el-table-column prop="description" label="接口描述" show-overflow-tooltip></el-table-column>
      <el-table-column prop="rules" label="接口规则" show-overflow-tooltip></el-table-column>
      <el-table-column label="操作" width="180">
        <template #default="scope">
          <el-button @click="editInterface(scope.row)" type="primary" size="small">修改</el-button>
          <el-button @click="deleteInterface(scope.row)" type="danger" size="small">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页条 -->
    <el-pagination
      v-model:current-page="pageNum"
      v-model:page-size="pageSize"
      :page-sizes="[3, 5, 10, 15]"
      layout="jumper, total, sizes, prev, pager, next"
      background
      :total="total"
      @size-change="onSizeChange"
      @current-change="onCurrentChange"
      style="margin-top: 20px; justify-content: flex-end"
    />
    <!-- 抽屉 -->
    <el-drawer v-model="visibleDrawer" :title="isEdit ? '修改接口' : '添加接口'" direction="rtl" size="50%">
      <!-- 添加接口表单 -->
      <el-form :model="interfaceModel" :rules="rules" label-width="100px">
        <el-form-item label="接口名称" prop="name">
          <el-input v-model="interfaceModel.name" placeholder="请输入接口名称"></el-input>
        </el-form-item>
        <el-form-item label="接口标识" prop="identifier">
          <el-input v-model="interfaceModel.identifier" placeholder="请输入接口标识"></el-input>
        </el-form-item>
        <el-form-item label="接口类型">
          <el-select v-model="interfaceModel.interfaceTypeId" placeholder="请选择接口类型">
            <el-option
              v-for="type in interfaceTypes"
              :key="type.id"
              :label="type.type"
              :value="type.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="所属对象">
          <el-select v-model="interfaceModel.objectTypeId" placeholder="请选择所属对象">
            <el-option
              v-for="object in objects"
              :key="object.id"
              :label="object.name"
              :value="object.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="IO类型">
          <el-select v-model="interfaceModel.ioTypeId" placeholder="请选择IO类型">
            <el-option
              v-for="ioType in ioTypes"
              :key="ioType.id"
              :label="ioType.type"
              :value="ioType.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="接口描述" prop="description">
          <el-input type="textarea" v-model="interfaceModel.description" placeholder="请输入接口描述"></el-input>
        </el-form-item>
        <el-form-item label="接口规则" prop="rules">
          <el-input type="textarea" v-model="interfaceModel.rules" placeholder="请输入接口规则"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="addInterface">{{ isEdit ? '修改' : '添加' }}</el-button>
        </el-form-item>
      </el-form>
    </el-drawer>
  </el-card>
</template>

<style lang="scss" scoped>
.page-container {
  min-height: 100%;
  box-sizing: border-box;

  .header {
    display: flex;
    align-items: center;
    justify-content: space-between;
  }
}
</style>